/**
 * 2024/01/01 - 2024/12/31
 **/
package com.snail.starter.validator;

import com.snail.starter.validator.annotation.SnailPhone;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * @author: (zg)
 * @Date: 2024/12/30 10:36
 * @Version: 1.0.0
 */
public class SnailPhoneValidator implements ConstraintValidator<SnailPhone, String> {

    private Pattern pattern;

    private boolean required;

    @Override
    public void initialize(SnailPhone annotation) {
        this.pattern = Pattern.compile(annotation.regex());
        this.required = annotation.required();
        ConstraintValidator.super.initialize(annotation);
    }

    @Override
    public boolean isValid(String phone, ConstraintValidatorContext constraintValidatorContext) {
        if (null == phone) {
            return !required;
        }
        return pattern.matcher(phone).matches();
    }

}